#!/usr/bin/python

import sys, os
from threading import Thread


SRC_DIR="~/Distributed-Graph-Query-Optimization/DGPM"
EXP_DIR="/scratch.1/jiewen/experiment/"
if os.getlogin() == "renkun":
    SRC_DIR = "~/dgpm2/DGPM/"
    EXP_DIR="/scratch.1/kv/"
DGPM_DIR= EXP_DIR + "DGPM/"
TMP_DIR= EXP_DIR + "tmp/"
PSQL_DIR= EXP_DIR + "/postgres/bin/"
if os.getlogin() == "renkun":
    PSQL_DIR = EXP_DIR + "postgres-install/bin/"
DB_PORT="6000"
if os.getlogin() == "renkun":
    DB_PORT = "5712"
DATASET=""
numberOfMachines=""

DRY_RUN = False

def doSomething(node, *args):
   print "Begin thread execution for host %s" %(node)
   # Sometimes previous execution did not clean up tmp tables, so we do it here to make sure
   os.system("ssh %s 'cd %s/scripts; sh kill_psql_session.sh'" %(node, SRC_DIR))
   for num in range(0, 15):
     os.system("ssh %s 'cd %s; psql -d %s-%s -p %s -c \"drop table n%s;\"' > /dev/null" %(node, PSQL_DIR, DATASET, numberOfMachines, DB_PORT, num))
     os.system("ssh %s 'cd %s; psql -d %s-%s -p %s -c \"drop table d%s;\"' > /dev/null" %(node, PSQL_DIR, DATASET, numberOfMachines, DB_PORT, num))
   # Copy DGPM to every machine
   os.system("ssh %s 'rm -rf %s'" %(node, DGPM_DIR))
   os.system("ssh %s 'cp -r %s %s'" %(node, SRC_DIR, EXP_DIR))
   # Clean up the tmp directory
   os.system("ssh %s 'rm -rf %s'" %(node, TMP_DIR))
   os.system("ssh %s 'mkdir %s'" %(node, TMP_DIR))

if __name__ == '__main__':

  numberOfMachines=sys.argv[1]
  DATASET=sys.argv[2]

  threads = []
  hostfile = "../config/" + numberOfMachines + "-nodes.txt"
  nodes = open(hostfile,'r').readlines()

  for i in nodes:
    node = i.strip()
    t = Thread(target=doSomething, args=(node,))
    threads.append(t)
    t.start()

  for thread in threads:
    thread.join

  print "All started"
